<template>
  <div class="consult-service">
    <div class="operate-bar">
      <el-button type="primary" plain size="small" @click="handleShowAddRecord"
        >新增记录</el-button
      >
    </div>
    <el-table :data="tableData" style="width: 100%" v-loading="tableLoading">
      <el-table-column
        fixed
        prop="consultTime"
        label="咨询日期"
        min-width="120"
      >
        <template slot-scope="scope">{{
          getConsultTime(scope.row.consultTime)
        }}</template>
      </el-table-column>
      <el-table-column
        prop="content"
        label="咨询内容"
        show-overflow-tooltip
        min-width="220"
      >
      </el-table-column>
      <el-table-column prop="fileList" label="附件" min-width="120">
        <template slot-scope="scope">
          <div v-if="scope.row.fileList">
            <div
              class="file"
              :title="item.name"
              v-for="(item, index) in scope.row.fileList"
              :key="index"
              @click="handlePreview(item)"
            >
              {{ item.name }}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="130">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button type="text" size="small" @click="handleRemove(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      title="新增咨询记录"
      width="700px"
      append-to-body
      :visible.sync="recordVisible"
      :before-close="handleClose"
    >
      <div class="form-container">
        <el-form
          class="form"
          :model="form"
          :rules="rules"
          ref="form"
          label-width="80px"
        >
          <el-form-item label="咨询时间" prop="consultTime">
            <el-date-picker
              placeholder="请选择咨询时间"
              v-model="form.consultTime"
              value-format="yyyy-MM-dd"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="咨询内容" prop="content">
            <el-input
              type="textarea"
              rows="6"
              v-model="form.content"
            ></el-input>
          </el-form-item>
          <el-form-item label="附件" prop="fileList">
            <el-upload
              :action="uploadAction"
              :accept="accept"
              :before-upload="beforeUpload"
              :on-success="handleUploadSuccess"
              :file-list="fileList"
              :on-remove="handleRemoveFile"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose" size="small">取 消</el-button>
        <el-button
          type="primary"
          size="small"
          :loading="addLoading"
          @click="handleConfirmAddRecord"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <PreviewFileDialog
      :visible.sync="previewVisible"
      :fileUrl="fileUrl"
      :fileName="fileName"
    ></PreviewFileDialog>
  </div>
</template>

<script>
import { serviceList, serviceSave, serviceUpdate, serviceDelete } from "@/api";
import PreviewFileDialog from "./PreviewFileDialog";
export default {
  components: { PreviewFileDialog },
  props: {
    selectedRow: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      uploadAction: "https://upload.yl1001.com/upload/files/save",
      accept: ".pdf,.PDF,.docx,.jpg,.png,.jpeg,.JPEG,.JPG,.PNG",
      tableData: [],
      recordVisible: false,
      previewVisible: false,
      tableLoading: false,
      addLoading: false,
      fileUrl: "",
      fileName: "",
      currentRowId: "",
      fileList: [],
      fileListArr: [],
      currentFile: {},
      form: {
        consultTime: "",
        content: "",
        fileUrl: "",
      },
      rules: {
        consultTime: [
          {
            type: "string",
            required: true,
            message: "请选择日期",
            trigger: "change",
          },
        ],
        content: [
          { required: true, message: "请填写咨询内容", trigger: "blur" },
        ],
      },
    };
  },
  mounted() {
    this.serviceListFn();
  },
  methods: {
    handlePreview(row) {
      this.fileUrl = row.url;
      this.fileName = row.name;
      this.previewVisible = true;
    },
    handleRemove(row) {
      this.$confirm("此操作将永久删除该条记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const params = { id: row.id };
          serviceDelete(params)
            .then((res) => {
              if (res.code == 200) {
                this.serviceListFn();
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
              } else {
                this.$message.error("删除失败!");
              }
            })
            .catch((err) => {
              this.$message.error(err.message);
            });
        })
        .catch(() => {});
    },
    handleEdit(row) {
      this.currentRowId = row.id;
      this.form.consultTime = row.consultTime;
      this.form.content = row.content;
      this.fileList = row.fileList;
      this.fileListArr = row.fileList;
      this.recordVisible = true;
    },
    handleConfirmAddRecord() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.addLoading = true;
          const params = {
            personId: this.selectedRow.personId,
            consultantId: this.selectedRow.consultantId,
            ...this.form,
          };
          if (this.fileListArr.length > 0) {
            params.fileUrl = JSON.stringify(this.fileListArr);
          } else {
            params.fileUrl = "";
          }
          const fn = this.currentRowId ? serviceUpdate : serviceSave;
          if (this.currentRowId) {
            params.id = this.currentRowId;
          }
          fn(params)
            .then((res) => {
              if (res.code == 200) {
                this.$message.success(
                  this.currentRowId ? "修改记录成功" : "新增记录成功"
                );
                this.recordVisible = false;
                this.serviceListFn();
              }
            })
            .finally(() => {
              this.addLoading = false;
              this.handleClose();
            });
        }
      });
    },
    handleShowAddRecord() {
      if (!this.selectedRow.consultantId) {
        this.$message.error("该用户还没帮定顾问");
        return;
      }
      this.recordVisible = true;
    },
    serviceListFn() {
      this.tableLoading = true;
      const params = {
        personId: this.selectedRow.personId,
        consultantId: this.selectedRow.consultantId,
      };
      serviceList(params)
        .then((res) => {
          if (res.code == 200) {
            res.data.forEach((item) => {
              item.fileList = item.fileUrl ? JSON.parse(item.fileUrl) : [];
            });
            this.tableData = res.data;
          }
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },
    handleRemoveFile(file) {
      const temp = this.fileListArr.find((item) => item.name === file.name);
      this.fileListArr.splice(this.fileListArr.indexOf(temp), 1);
    },
    handleUploadSuccess(file) {
      this.fileListArr.push({
        name: this.currentFile.name,
        url: file.data[0],
      });
    },
    beforeUpload(files) {
      if (
        [
          "application/pdf",
          "application/vnd.openxmlformats-officedocument.presentationml.presentation",
          "application/msword",
          "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
          "application/vnd.ms-powerpoint",
          "image/jpeg",
          "image/jpg",
          "image/png",
        ].indexOf(files.type) == -1
      ) {
        this.$message.error(
          "请上传正确的文本格式文件，如pdf doc docx png jpg jpeg"
        );
        return false;
      }
      if (files.size > 10 * 1024 * 1024) {
        this.$message.error("请上传小于10M的文件");
        return false;
      }
      this.currentFile = files;
      return true;
    },
    getConsultTime(time) {
      if (!time) {
        return "-";
      }
      return time.slice(0, 10);
    },
    handleClose() {
      this.currentRowId = "";
      this.form.content = "";
      this.form.consultTime = "";
      this.form.fileUrl = "";
      this.fileList = [];
      this.fileListArr = [];
      this.recordVisible = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.consult-service {
  padding-right: 14px;
  .operate-bar {
    margin-bottom: 14px;
  }
  .file {
    cursor: pointer;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    width: 100%;
    padding: 3px;
    &:hover {
      color: #7153ff;
    }
  }
  .form-container {
    .form {
      ::v-deep .el-form-item {
        margin-bottom: 22px !important;
      }
    }
  }
}
</style>
